package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.utils.TimeUtil;
import com.xiaocz.common.widgets.load.LoadFactory;
import com.xiaocz.common.widgets.load.core.LoadManager;
import com.xiaocz.common.widgets.load.view.AbsView;
import com.xiaocz.common.widgets.recycler.RecyclerViewAdapter;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.adapter.OrderListAdapter;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.model.OrderInfo;
import com.xiaocz.hblsubstitutedriving.widget.EmptyView;
import com.xiaocz.hblsubstitutedriving.widget.ErrorView;
import com.xiaocz.hblsubstitutedriving.widget.LoadingView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 订单列表
 */
public class OrderListActivity extends BaseActivity {

    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.btn_right)
    TextView btnRight;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recycler_view)
    public RecyclerView mRecyclerView;

    /**
     * DATA
     */
    private LoadManager mLoadManager;
    private OrderListAdapter orderListAdapter;

    public static void show(Context context) {
        Intent intent = new Intent(context, OrderListActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_list;
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
        mLoadManager = LoadFactory.getInstance().register(refreshLayout, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                webMyOrder();
            }
        });
        setRefresh();
        dateValue=TimeUtil.stamp2Time(TimeUtil.getStringStamp(),Common.DateType.dateYm);
        btnRight.setText(dateValue);
        btnRight.setVisibility(View.VISIBLE);
    }

    private int page = 1;

    private void setRefresh() {
        // 下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
                page=1;
                webMyOrder();
            }
        });
        //加载更多
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore();
                page++;
                webMyOrder();
            }
        });
        webMyOrder();
    }

    @Override
    protected void initData() {
        super.initData();
        mTitle.setText("我的订单");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        orderListAdapter = new OrderListAdapter(new RecyclerViewAdapter.AdapterListenerImpl<OrderInfo>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<OrderInfo> holder, OrderInfo data) {
                super.onItemClick(holder, data);
                if("1".equals(data.getPaystatus()) && data.getOrderstatus()==3){
                    OrderGatheringActivity.show(mContext,data.getOrderNo());
                }else {
                    OrderDetailsActivity.show(mContext,data.getOrderNo());
                }
            }
        });
        mRecyclerView.setAdapter(orderListAdapter);
    }

    @OnClick({R.id.btn_right})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_right:
                setTime();
                break;
        }
    }


    private String dateValue;
    /**
     * 我的订单
     */
    private void webMyOrder() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("PageIndex", page);
        asyncHttpPostFormData.addFormData("date",dateValue);
        asyncHttpPostFormData.addFormData("PageSize", Common.Constant.pageSize);
        okHttpClient.post(Common.Constant.API_IP+"api/Order/getOrderList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<List<OrderInfo>>>() {
                }.getType();
                RspModel<List<OrderInfo>> rspModel = getAnalysisBase(mLoadManager, response, type, "我的请求");
                if (rspModel == null) {
                    mLoadManager.showStateView(EmptyView.class);
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            if (page == 1) {
                                orderListAdapter.replace(rspModel.getData());
                            } else {
                                orderListAdapter.add(rspModel.getData());
                            }
                        } else {
                            if (page == 1) {
                                mLoadManager.showStateView(EmptyView.class);
                            } else {
                                App.getInstance().showMessage("已到底啦！");
                            }
                        }
                        break;
                    default:
                        mLoadManager.showStateView(ErrorView.class);
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 开始时间
     */
    private void setTime() {
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (TimeUtil.getLongStamp() + 180 > date.getTime() / 1000) {
                    dateValue=TimeUtil.stamp2Time(date, Common.DateType.dateYm);
                    btnRight.setText(dateValue);
                    page=1;
                    webMyOrder();
                } else {
                    App.getInstance().showMessage("请选择正确的时间!");
                }
            }
        }).setType(new boolean[]{true, true, false, false, false, false}).build();
        pvTime.show();
    }

}
